#include "Heap.h"
void HeapInit(HP* php)
{
	assert(php);
	php->a = (HPDateType*)malloc(sizeof(HPDateType)*4);
	assert(php->a);
	php->size = 0;
	php->capacity = 4;
}
void Swap(HPDateType* p1, HPDateType* p2)
{
	HPDateType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
void AdjustUp(HP* php, int child)
{
	assert(php);
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (php->a[child] > php->a[parent])
		{
			Swap(&php->a[child], &php->a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
	
}
void HeapDestroy(HP* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}
void HeapPush(HP* php,HPDateType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		HPDateType* tmp = (HPDateType*)realloc(php->a,sizeof(HPDateType) * php->capacity * 2);
		assert(tmp);
		php->a = tmp;
		php->capacity *= 2;
	}
	php->a[php->size++] = x;
	AdjustUp(php,php->size - 1);
}
void AdjustDown(HP* php, int n,int parent)
{
	assert(php);
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && php->a[child] < php->a[child + 1])
		{
			child++;
		}
		if (php->a[parent] < php->a[child])
		{
			Swap(&php->a[parent], &php->a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;

	}
}
void HeapPop(HP* php)
{
	assert(php);
	assert(!HeapEmpty(php));
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;

	
	AdjustDown(php,php->size,0);
}
HPDateType HeapTop(HP* php)
{
	assert(php);
	return php->a[0];
}
bool HeapEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}
int HeapSize(HP* php)
{
	assert(php);
	return php->size;
}